package com.xp.tinyurl.admin.auth;

import com.xp.tinyurl.common.exception.AuthException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description jwt auth
 * @Author chengguo.pei
 * @Date 2021/9/26 14:29
 */
@Slf4j
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserThreadLocal userThreadLocal;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (HttpMethod.OPTIONS.name().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String token = jwtUtil.getToken(request);

        log.info("token => {}", token);

        if(StringUtils.isEmpty(token)){
            log.error("非法访问，未查询到token");
            throw new AuthException("非法访问，未查询到token");
        }
        String userName = null;
        try {
            userName = jwtUtil.getClaimValue(token, "name");
        }catch (Exception e){
            log.error("token过期", e);
        }
        if(StringUtils.isEmpty(userName)){
            log.error("token未通过认证：{}", token);
            throw new AuthException("token未通过认证");
        }

        userThreadLocal.set(userName);

        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        userThreadLocal.remove();
        super.postHandle(request, response, handler, modelAndView);
    }
}
